package cn.xz.gobang.dialog

import android.view.Gravity
import android.widget.EditText
import android.widget.TextView
import cn.xz.gobang.R
import cn.xz.gobang.base.BaseDialogRxFragment
import cn.xz.gobang.bean.*
import cn.xz.gobang.net.OkHttpUtil
import cn.xz.gobang.util.GetDataUtils
import cn.xz.gobang.util.JsonUtil
import cn.xz.gobang.util.SessionUtils
import okhttp3.FormBody
import okhttp3.RequestBody

/**
 * 反馈弹窗
 * */
class FkDialog: BaseDialogRxFragment() {

    private var tvCancel: TextView? = null
    private var tvOver: TextView? = null
    private var etInput: EditText? = null

    companion object {
        fun newInstance(
        ): FkDialog {
            return FkDialog()
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.item_fk
    }

    override fun configDialog() {
        this.setDialogSize(gravity = Gravity.CENTER,width = 300)
    }

    override fun initViews() {

        dialog?.let {
            tvOver = it.findViewById(R.id.tv_over)
            tvCancel = it.findViewById(R.id.tv_cancel)
            etInput = it.findViewById(R.id.et_input)
        }

        //点击外部不隐藏
        dialog?.setCancelable(false)
        dialog?.setCanceledOnTouchOutside(false)
        //点击事件
        initEvent()
    }


    private fun initEvent(){
        if (tvOver != null){
            tvOver?.setOnClickListener {
                putTxt()
                dismiss()
            }
        }
        if (tvCancel != null){
            tvCancel?.setOnClickListener {
                dismiss()
            }
        }
    }

    private fun putTxt(){
        if (etInput != null && etInput!!.text.toString().isNotEmpty()){
            //获取所有反馈信息
            val requestBody: RequestBody = FormBody.Builder()
                .add("txtName", CommonLib.FeedBack)
                .build()
            OkHttpUtil.toPost(CommonLib.getMUrl + CommonLib.GET_ALL_USER,requestBody,object :
                OkHttpUtil.RequestSuccess<FeedBack> {
                override fun success(bean: FeedBack?) {
                    if (bean!= null){
                        bean.data.add(FeedBackData(SessionUtils.getString(SessionUtils.USER_ID,""),etInput!!.text.toString()))
                        putContent(bean)
                    }
                }
                override fun error() {
                }
            },FeedBack::class.java)
        }
    }

    private fun putContent(f: FeedBack){
        //更新反馈数据
        GetDataUtils.onWriteData(CommonLib.FeedBack,JsonUtil.serializeAsString(f),object :GetDataUtils.OnWriteDataListener{
            override fun success() {

            }
        })
    }

}